package com.seed.commons.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
 * 随机类
 * 作者：Young
 * 创建时间：Nov 9, 2009 12:28:27 AM
 * 类说明：
 */
public class RandomUtil {
	
	public static void main(String[] args) {
		calProRunTime() ;
	}

	/**
	 * 根据给定长度产生随机([a-z][A-Z][0-9])
	 * 性能好
	 * @param length
	 * @return
	 */
	public static String getRandomString(int length) {
		String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();

		for (int i = 1; i <= length; i++) {
			int number = random.nextInt(str.length());

			sb.append(str.charAt(number));
		}
		return sb.toString();
	}
	
	/**
	 * 根据给定长度产生随机([a-z][A-Z][0-9])
	 * 性能差
	 * @param length
	 * @return
	 */
	public static String getRandomString2(int length) {
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		
		for (int i = 0; i < length; ++i) {
			int number = random.nextInt(3);
			long result = 0;

			switch (number) {
			case 0:
				result = Math.round(Math.random() * 25 + 65);
				sb.append(String.valueOf((char) result));
				break;
			case 1:
				result = Math.round(Math.random() * 25 + 97);
				sb.append(String.valueOf((char) result));
				break;
			case 2:
				sb.append(String.valueOf(new Random().nextInt(10)));
				break;
			}
		}
		return sb.toString();
	}
	
	/**
	 * 根据给定长度产生随机([0-9])
	 * 性能好
	 * @param length
	 * @return
	 */
	public static String getRandomNum(int length) {
		String str = "0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();

		for (int i = 1; i <= length; i++) {
			int number = random.nextInt(str.length());

			sb.append(str.charAt(number));
		}
		return sb.toString();
	}
	
	/**
	 * 当前年月日 + 4位毫秒 + 根据给定长度产生随机(0~9)
	 * @param length
	 * @return
	 */
	public static String getDateNum(int length) {
		String str = "0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();

		for (int i = 1; i <= length; i++) {
			int number = random.nextInt(str.length());

			sb.append(str.charAt(number));
		}
		String newTime = new SimpleDateFormat("yyyyMMddSSSS").format(new Date());
		
		return newTime+sb.toString();
	}
	
	/** 计算程序的运行时间 */
	public static void calProRunTime() {
		long startTime = System.currentTimeMillis(); //获取开始时间   
		
		System.out.println(getRandomString(6));
		
		long endTime=  System.currentTimeMillis(); //获取结束时间   
		System.out.println("程序运行时间： "+(endTime-startTime)+"ms");
	}


}
